#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <pthread.h>
#include <signal.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "Common.hpp"

int sockfd = -1;
struct sockaddr_in server;

void ClientQuit(int signo)
{
    const std::string quit = " ...离线";
    ::sendto(sockfd, quit.c_str(), quit.size(), 0, CONV(&server), sizeof(server));

    exit(0);
}

// 新线程收消息
void *Receive(void *args)
{
    while (true)
    {
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        char buffer[1024];
        int n = ::recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, CONV(&temp), &len);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cerr << buffer << std::endl;
        }
    }
}

// 运行方式: ./client_uddp serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " serverip serverport" << std::endl;
        Die(USAGE_ERR);
    }
    ::signal(2, ClientQuit);
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    // 1. 创建socket
    sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "socket error" << std::endl;
        Die(SOCKET_ERR);
    }

    // 2. 填充server信息(IP + 端口号)
    std::memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;                            // 网络通信
    server.sin_port = ::htons(serverport);                  // 端口: 主机序列->网络序列
    server.sin_addr.s_addr = ::inet_addr(serverip.c_str()); // IP: 字符串->字节序列->网络序列

    // 3. 客户端启动的时候, 给服务器推送消息
    const std::string online = " ...上线";
    ::sendto(sockfd, online.c_str(), online.size(), 0, CONV(&server), sizeof(server));

    pthread_t tid;
    pthread_create(&tid, nullptr, Receive, nullptr); // 创建新线程: 并发实现发收消息

    while (true)
    {
        std::cout << "Please Enter# ";
        std::string message;
        std::getline(std::cin, message);

        // 4. 主线程发送信息
        ::sendto(sockfd, message.c_str(), message.size(), 0, CONV(&server), sizeof(server));
    }

    return 0;
}